package com.example.f8399.testdemo.activity;

import android.Manifest;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.view.View;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.blankj.utilcode.util.ToastUtils;
import com.example.f8399.testdemo.BaseActivity;
import com.example.f8399.testdemo.Constant;
import com.example.f8399.testdemo.R;
import com.example.f8399.testdemo.databinding.ActivityLbsBinding;
import com.example.f8399.testdemo.listener.MyLocationListener;

import java.util.Arrays;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * @author lcfeng
 * @description 有关调用百度lbs的UI.
 * <p>
 * http://lbsyun.baidu.com/index.php?title=android-locsdk/guide/create-project/key
 * @date 2018/7/9 17:01.
 **/
public class LbsActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks,EasyPermissions.RationaleCallbacks{

    public LocationClient mLocationClient = null;
    private MyLocationListener mListener = new MyLocationListener();

    ActivityLbsBinding mBinding;
    private String[] permissList = new String[]{
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_lbs);
        mBinding.setAc(this);

        initView();
    }




    public void getLocation(View view) {
        if (EasyPermissions.hasPermissions(this, permissList)) {
            getRealLocation(false);
        }else {
            EasyPermissions.requestPermissions(this, getString(R.string.permission_warning), Constant.PERMISS_REQUEST_CODE,permissList);
        }
    }

    public void stopLocation(View view) {
        if (mLocationClient.isStarted()) {
            mLocationClient.stop();
        }else {
            ToastUtils.showShort("定位已关闭");
        }
    }

    private void initView() {
        LocationClientOption option = customLocationOption();
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.setLocOption(option);
        mLocationClient.registerLocationListener(mListener);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        //查询是否有权限被永久的禁用了（Permanent）
        if (EasyPermissions.somePermissionPermanentlyDenied(this,perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            ToastUtils.showShort("what happened?");
        }
    }

    /**
     * 启动定位
     * @param isRestart true:使用restart 方法，为了适配7.0版本，false:使用start方法，为了第一次启动
     */
    public void getRealLocation(boolean isRestart) {
        if (isRestart) {
            mLocationClient.restart();
        }else {
            mLocationClient.start();
        }

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(1);
            }
        },10000);//10秒中后自动关闭服务，手机不同导致定位所需时间也是有差距，所以给的时间长点
    }

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            mLocationClient.stop();
        }
    };


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 定制化定位配置
     *
     * @return 配置
     */
    private LocationClientOption customLocationOption() {
        LocationClientOption option = new LocationClientOption();

        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        //可选，默认gcj02，设置返回的定位结果坐标系
        option.setCoorType("bd09ll");
        int span = 1000;
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setScanSpan(span);
        //可选，设置是否需要地址信息，默认不需要
        option.setIsNeedAddress(true);
        //可选，默认false,设置是否使用gps
        option.setOpenGps(true);
        //可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setLocationNotify(false);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIsNeedLocationPoiList(true);
        //可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.setIgnoreKillProcess(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集
        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        option.setEnableSimulateGps(false);

        return option;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            if (mLocationClient.isStarted()) {
                mLocationClient.stop();
            }
            mLocationClient = null;
        }
    }


    @Override
    public void onRationaleAccepted(int requestCode) {
        ToastUtils.showShort("你接受了");
    }

    @Override
    public void onRationaleDenied(int requestCode) {
        ToastUtils.showShort("你拒绝了");
    }
}
